package utils;

import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;


public class BatchSqlUtil {


    /**
     * 批量更新
     * @param con 数据库链接
     * @param sql 预编译的sql
     * @param paramList  参数列表
     * @param batchNum 批量执行的数量
     */
    public static String batchDo(Connection con, List<String> sql, Integer batchNum, File sqlFile){

        try( Statement statement = con.createStatement()){
            //已经add sql 的条数
            int sqlSize = 0;

            for (int i = 0; i < sql.size(); i++) {
                String tempSql = sql.get(i);
                if(tempSql.endsWith(";")){
                    tempSql = tempSql.substring(0, tempSql.length() - 1);
                }
                FileUtil.appendString(tempSql + "\n", sqlFile, "UTF-8");
                FileUtil.appendString("------------------------------\n", sqlFile, "UTF-8");
                statement.addBatch(tempSql);
                if(sqlSize == batchNum){
                    statement.executeBatch();
                    sqlSize = 0;
                    statement.clearBatch();
                }
            }

            if((sql.size())%batchNum != 0){
                statement.executeBatch();
                statement.clearBatch();
            }

            con.commit();
            return "";
        }catch (Exception ex){
            ex.printStackTrace();
            return ExceptionUtil.writeLog(ex);
        }
    }


}
